package com.baikeyang.bike.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baikeyang.bike.bean.BikeBean;
import com.baikeyang.bike.service.IXABikeService;
import com.baikeyang.bike.util.RedisUtil;
import com.baikeyang.bike.util.StringUtil;
import com.baikeyang.bike.ws.client.xabike.findabnormalsite.IAbnormalSiteService;
import com.baikeyang.bike.ws.client.xabike.findabnormalsite.IAbnormalSiteServicePortType;
import com.baikeyang.bike.ws.client.xabike.findbike.IBikeSitesService;
import com.baikeyang.bike.ws.client.xabike.findbike.IBikeSitesServicePortType;
import com.baikeyang.bike.ws.client.xabike.tradecount.IBikeTradeCountService;
import com.baikeyang.bike.ws.client.xabike.tradecount.IBikeTradeCountServicePortType;
import com.baikeyang.bike.ws.client.xabike.traderecord.IBikeTradeRecordService;
import com.baikeyang.bike.ws.client.xabike.traderecord.IBikeTradeRecordServicePortType;

@Service("xaBikeService")
public class XABikeServiceImpl implements IXABikeService {
	
	private static final Logger logger = Logger.getLogger(XABikeServiceImpl.class);

	@Override
	public void sayHello(String str) {
		IBikeTradeCountServicePortType bikeService = new IBikeTradeCountService().getIBikeTradeCountServiceHttpPort();
		String bikeCount = bikeService.findBikeTradeCount();
		System.out.println(bikeCount);
		System.out.println("你要说的话是:"+str);
	}

	@Override
	public String findBikeTradeCount() {
		IBikeTradeCountServicePortType bikeService = new IBikeTradeCountService().getIBikeTradeCountServiceHttpPort();
		String bikeCount = bikeService.findBikeTradeCount();
		return bikeCount;
	}
	
	@Override
	public String findBikeNormalSite(){
		IBikeSitesServicePortType bikeSiteService = new IBikeSitesService().getIBikeSitesServiceHttpPort();
		String bikeSite = bikeSiteService.findBikeSites();
		return bikeSite;
	}
	
	@Override
	public List<BikeBean> getBikeNormalSite(){
		List<BikeBean> bikesNormal = new ArrayList<BikeBean>();
		try {
			String key = "bike-normal-position";
			Map<String, String> keys = RedisUtil.hgetKeys(key);
			Iterator<Entry<String, String>> iterator = keys.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> en = iterator.next();
				String siteid = en.getKey();
				String value = RedisUtil.getString("bike-site-"+siteid);
				if(StringUtil.isNotEmpty(value)){
					bikesNormal.add(JSON.parseObject(value, BikeBean.class));
				}
			}
		} catch (Exception e) {
			logger.error("获取正常车辆站点时发生异常", e);
		}
		return bikesNormal;
	}
	
	@Override
	public String findBikeAbnormalSite(){
		IAbnormalSiteServicePortType abnormalSite = new IAbnormalSiteService().getIAbnormalSiteServiceHttpPort();
		String bikeSite = abnormalSite.findAbnormalSites();
		return bikeSite;
	}
	
	public List<BikeBean> getBikeAbnormalSite(){
		List<BikeBean> bikesAbnormal = new ArrayList<BikeBean>();
		try {
			String key = "bike-abnormal-position";
			Map<String, String> keys = RedisUtil.hgetKeys(key);
			Iterator<Entry<String, String>> iterator = keys.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String, String> en = iterator.next();
				String siteid = en.getKey();
				String value = RedisUtil.getString("bike-site-"+siteid);
				if(StringUtil.isNotEmpty(value)){
					bikesAbnormal.add(JSON.parseObject(value, BikeBean.class));
				}
			}
		} catch (Exception e) {
			logger.error("获取异常车辆站点时发生异常", e);
		}
		return bikesAbnormal;
	}

	@Override
	public String findBikeTradeRecords(String cardNo) {
		IBikeTradeRecordServicePortType tradeRecordSerivce = new IBikeTradeRecordService().getIBikeTradeRecordServiceHttpPort();
		String tradeRecord = tradeRecordSerivce.findBikeTradeRecords(cardNo);
		return tradeRecord;
	}

	@Override
	public void synchronizeBikeSitePosition() throws Exception {
		synchronizeBikeAbnormalSitePosition();// 异常站点信息
		synchronizeBikeNormalSitePosition();// 正常站点信息
	}
	
	@Override
	public void synchronizeBikeAbnormalSitePosition() throws Exception {
		String key = "bike-abnormal-position";
		List<String> fields = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
		// 异常站点
		String abnormal = findBikeAbnormalSite();
		List<BikeBean> bikesAbnormal  = JSONArray.parseArray(abnormal, BikeBean.class);
		for (int i = 0; i < bikesAbnormal.size(); i++) {
			BikeBean bike = bikesAbnormal.get(i);
			if(null != bike){
				fields.add(bike.getSiteid());
				values.add(bike.getLongitude() + "," + bike.getLatitude());
			}
		}
		try {
			logger.debug("本次共同步" + fields.size() + "条数据。");
			RedisUtil.setHSet(key, fields, values);
        } catch (Exception e) {
        	logger.error("车站位置信息 数据同步异常.", e);
        }
	}
	@Override
	public void synchronizeBikeNormalSitePosition() throws Exception {
		String key = "bike-normal-position";
		List<String> fields = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
		// 正常站点
		String normal = findBikeNormalSite();
		List<BikeBean> bikesNormal = JSONArray.parseArray(normal, BikeBean.class);
		for (int i = 0; i < bikesNormal.size(); i++) {
			BikeBean bike = bikesNormal.get(i);
			if(null != bike){
				//TODO 经纬度重复，导致部分站点位置丢失
				fields.add(bike.getSiteid());
				values.add(bike.getLongitude() + "," + bike.getLatitude());
			}
		}
		try {
			logger.debug("本次共同步" + fields.size() + "条数据。");
			RedisUtil.setHSet(key, fields, values);
        } catch (Exception e) {
        	logger.error("车站位置信息 数据同步异常.", e);
        }
	}

	public static void main(String[] args) {
		Date start = new Date();
		try {
//			XABikeServiceImpl x = new XABikeServiceImpl();
//			x.synchronizeBikeNormalSitePosition();// 耗时 61872 毫秒； 本次共同步1692条数据。
//			x.synchronizeBikeAbnormalSitePosition();// 耗时 4086 毫秒；本次共同步28条数据。
//			List list = x.getAllBikePostions();
//			System.out.println(list.size());
			
//			String key = "bike-abnormal-position";
//			Map<String, String> keys = RedisUtil.hgetKeys(key);
//			System.out.println(keys.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
		Date end = new Date();
		System.out.println(end.getTime()-start.getTime());
		
//		start = new Date();
//		try {
//			XABikeServiceImpl x = new XABikeServiceImpl();
//			x.synchronizeBikeSite();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		end = new Date();
//		System.out.println(end.getTime()-start.getTime());
		
		
//		XABikeServiceImpl xaBike = new XABikeServiceImpl();
//		String str = xaBike.findBikeTradeRecords("07405244");
//		System.out.println(str);
		
		// {"emptynum":"29","latitude":"34.323807","location":"文景路与凤城二路十字向东50米路南","locknum":"30",
		// "longitude":"108.944631","siteState":"1","siteid":"1022","sitename":"北郊赛格电脑城"}
//		BikeBean bike = new BikeBean();
//		bike.setSiteid("1002");
//		bike.setLatitude("108.96173");
//		bike.setLatitude("34.347436");
//		bike.setEmptynum("10");
//		bike.setLocknum("20");
//		bike.setSitename("市人大");
//		bike.setSiteState("1");
//		bike.setLocation("文景路与凤城二路十字向东50米路南");
//		System.out.println(JSON.toJSON(bike));
	}

	@Override
	public void synchronizeBikeSite() {
		synchronizeBikeNormalSite();
		synchronizeBikeAbnormalSite();
	}
	
	public void synchronizeBikeNormalSite(){
		List<String> keys = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
		// 正常站点
		String normal = findBikeNormalSite();
		List<BikeBean> bikesNormal = JSONArray.parseArray(normal, BikeBean.class);
		for (int i = 0; i < bikesNormal.size(); i++) {
			BikeBean bike = bikesNormal.get(i);
			if(null != bike){
				String key = "bike-site-"+bike.getSiteid();
				keys.add(key);
				bike.setSiteState("1");
				values.add(JSON.toJSONString(bike));
			}
		}
		try {
            RedisUtil.setStrings(keys, values);
        } catch (Exception e) {
        	logger.error("同步 正常车辆信息 数据异常.", e);
        }
	}
	
	public void synchronizeBikeAbnormalSite(){
		List<String> keys = new ArrayList<String>();
        List<String> values = new ArrayList<String>();
        // 异常站点
		String abnormal = findBikeAbnormalSite();
		List<BikeBean> bikesAbnormal  = JSONArray.parseArray(abnormal, BikeBean.class);
		for (int i = 0; i < bikesAbnormal.size(); i++) {
			BikeBean bike = bikesAbnormal.get(i);
			if(null != bike){
				// {"emptynum":"10","latitude":"34.347436","location":"","locknum":"20","longitude":"108.96173","siteState":"1","siteid":"1003","sitename":"市人大"}
				String key = "bike-site-"+bike.getSiteid();
				keys.add(key);
				bike.setSiteState("0");
				values.add(JSON.toJSONString(bike));
			}
		}
		try {
            RedisUtil.setStrings(keys, values);
        } catch (Exception e) {
        	logger.error("同步 异常车辆信息 数据异常.", e);
        }
	}

	@Override
	public List<BikeBean> getAllBikes() throws Exception {
		List<BikeBean> bikes = new ArrayList<BikeBean>();
		String key = "bike-site-*";
		Set<String> keys = RedisUtil.getKeys(key);
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {  
			String str = it.next();
			String value = RedisUtil.getString(str);
			BikeBean bb = new BikeBean();
			bb = JSON.parseObject(value, BikeBean.class);
			bikes.add(bb);
		}
		return bikes;
	}
	
	public List<BikeBean> getAllBikePostions() {
		List<BikeBean> bikes = new ArrayList<BikeBean>();
		try {
			String abnormalKey = "bike-abnormal-position";
			Map<String, String> abnormalKeys = RedisUtil.hgetKeys(abnormalKey);
			Iterator<Entry<String, String>> it = abnormalKeys.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, String> en = it.next();
				BikeBean bb = new BikeBean();
				bb.setSiteState("0");
				bb.setSiteid(en.getKey());
				if(StringUtil.isNotEmpty(en.getValue())){
					try{
						bb.setLongitude(en.getValue().split(",")[0]);
						bb.setLatitude(en.getValue().split(",")[1]);
					}catch(Exception e){
						System.out.println(en.getValue());
					}
				}
				bikes.add(bb);
			}
			
		} catch (Exception e) {
			logger.error("获取异常站点位置信息时发生异常", e);
		}
		try {
			String normalKey = "bike-normal-position";
			Map<String, String> normalKeys = RedisUtil.hgetKeys(normalKey);
			Iterator<Entry<String, String>> it = normalKeys.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, String> en = it.next();
				BikeBean bb = new BikeBean();
				bb.setSiteState("1");
				bb.setSiteid(en.getKey());
				if(StringUtil.isNotEmpty(en.getValue())){
					try{
						bb.setLongitude(en.getValue().split(",")[0]);
						bb.setLatitude(en.getValue().split(",")[1]);
					}catch(Exception e){
						System.out.println(en.getValue());
					}
				}
				bikes.add(bb);
			}
		} catch (Exception e) {
			logger.error("获取正常站点位置信息时发生异常", e);
		}
		return bikes;
	}

	@Override
	public BikeBean getBikeSiteById(String siteId) {
		BikeBean bb = new BikeBean();
		if(StringUtil.isNotEmpty(siteId)){
			try {
				String value = RedisUtil.getString("bike-site-"+siteId);
				if(StringUtil.isNotEmpty(value)){
					bb = JSON.parseObject(value, BikeBean.class);
				}
			} catch (Exception e) {
				logger.error("根据ID[" + siteId + "]获取站点信息时发生异常", e);
			}
		}
		return bb;
	}
	

}
